package com.szh.zx.javacorecorret.chap2.one;


import java.util.concurrent.CountDownLatch;
// 章节 2.1.4
// 本节要使用 CountDownLatch 类来实现所有的线程，呈wait后再统一唤醒的效果，此实验大量使用 CountDownLatch类来实现业务要求的同步效果
public class CountDownLatchTest4{
	public static void main(String[] args) throws InterruptedException {
		CountDownLatch comingTag = new CountDownLatch(10);
		CountDownLatch waitTag = new CountDownLatch(1);
		CountDownLatch waitRunTag = new CountDownLatch(10);
		CountDownLatch beginTag = new CountDownLatch(1);
		CountDownLatch endTag = new CountDownLatch(10);

		MyThread4[] threadArray = new MyThread4[10];

		for (int i = 0; i < threadArray.length; i++) {
			threadArray[i] = new MyThread4(comingTag, waitTag, waitRunTag,
					beginTag, endTag);
			threadArray[i].start();
		}
		System.out.println("裁判员在等待选手的到来！");
		comingTag.await();
		System.out.println("裁判看到所有运动员来了，各就各位前“巡视”用时5秒");
		Thread.sleep(5000);
		waitTag.countDown();
		System.out.println("各就各位！");
		waitRunTag.await();
		Thread.sleep(2000);
		System.out.println("发令枪响起！");
		beginTag.countDown();
		endTag.await();
		System.out.println("所有运动员到达，统计比赛名次！");
	}
}

class MyThread4  extends Thread{

	private CountDownLatch comingTag;// 裁判等待所有运动员到来
	private CountDownLatch waitTag;// 等待裁判说准备开始
	private CountDownLatch waitRunTag;// 等待起跑
	private CountDownLatch beginTag;// 起跑
	private CountDownLatch endTag;// 所有运动员到达终点
	@Override
	public void run() {
		try {
			System.out.println("运动员使用不同的交通工具不同的速度到达起跑点，正向这走");
			Thread.sleep((int)(Math.random()*10*1000));

			System.out.println(Thread.currentThread().getName()+"到达起跑点");
			comingTag.countDown();
			System.out.println("等待裁判说准备");

			waitTag.await();
			System.out.println("各就各位");
			Thread.sleep((int)(Math.random()*10*1000));
			waitRunTag.countDown();
			beginTag.await();
			System.out.println(Thread.currentThread().getName()+"运动员起跑，赛程过程不确定");
			Thread.sleep((int)(Math.random()*10*1000));
			endTag.countDown();
			System.out.println(Thread.currentThread().getName()+"运动员到达终点");
		}catch (InterruptedException e){
			e.printStackTrace();
		}

	}
	public MyThread4(CountDownLatch comingTag, CountDownLatch waitTag, CountDownLatch waitRunTag, CountDownLatch beginTag, CountDownLatch endTag) {
		this.comingTag = comingTag;
		this.waitTag = waitTag;
		this.waitRunTag = waitRunTag;
		this.beginTag = beginTag;
		this.endTag = endTag;
	}


}